import axios from 'axios'
import qs from 'qs'
// axios config https://github.com/axios/axios#request-config
// const myApi = 'https://www.easy-mock.com/mock/58fff6e5739ac1685205acb1/data/'
// 'http://jr.duduapp.net/api/' : 'http://192.168.1.116/api/'
// const pro = process.env.NODE_ENV === 'production'
// const test = process.env.NODE_TEST === 'test'
const urlType = process.env.NODE_URL;
let proxyUrl = 'https://index-api.meadin.com';
switch(urlType) {
  case "dev": 
    // proxyUrl = "http://10.10.29.251:8081";
    proxyUrl = "http://10.10.29.246:8081";
    break;
  case "test":
    proxyUrl = "http://10.10.29.205:6300";
    break;
  default:
    break;
}
// const pt = dev ? 'http://10.10.29.251:8081' : ((pro && !test) ? 'https://index-api.meadin.com' : 'http://10.10.29.205:7080');
// const pt = pro ? (test ? 'http://10.10.29.205:7080' : 'https://index-api.meadin.com') : (urlType === "prod" ? 'https://index-api.meadin.com' : (urlType === "dev" ? "http://10.10.29.251:8081" : (test ? 'http://10.10.29.205:7080' : 'https://index-api.meadin.com')))
const pt = proxyUrl;
// const pt = pro ? (test ? 'http://10.10.29.205:6300' : 'https://index-api.meadin.com') : proxyUrl;
// console.info(`< res >: -----${pt}-----`);
console.log(`http: ${pt}`);
const callApi = (url, method, data, isServer = false, options = {}) => {
  const opts = { ...options }
  console.log(`baseURL: ${isServer ? pt : '/'}`);
  return axios(Object.assign({}, {
    baseURL: isServer ? pt : '/',
    url,
    method,
    headers: {
      'Access-Control-Allow-Origin': '*'
    },
    params: method === 'get' ? data : {}, // 添加在请求URL后面的参数
    paramsSerializer: (params) => {
      return qs.stringify(params, { arrayFormat: 'brackets' })
    },
    data: method !== 'get' ? data : {}, // 适用于 PUT POST PATCH
    withCredentials: true, // 请求时是否携带cookie
  }, opts)).then(data => {
    return data.data;
  }).catch((error ) => {
    console.log(url);
    console.error('http', error)
  })
}

export default {
  callApi,
  get: (url, data = {}, isServer) => callApi(url, 'get', data, isServer),
  put: (url, data = {}, isServer) => callApi(url, 'put', data, isServer),
  post: (url, data = {}, isServer) => callApi(url, 'post', data, isServer),
  delete: (url, data = {}, isServer) => callApi(url, 'delete', data, isServer),
}
